#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : mocobk
# @Email  : mailmzb@qq.com
# @Time   : 2020/8/13 12:29
import json

from mitmproxy import ctx
from mitmproxy.http import HTTPFlow
from mitmdump import DumpMaster, Options
from redis import Redis

msgChan = "proxy/msg/chan"
redisCli = Redis(host="127.0.0.1", port=6379, encoding="utf8", decode_responses=True)


def request(flow: HTTPFlow):
    ctx.log.info(flow.request.path)


def response(flow: HTTPFlow):
    # ctx.log.info("path:".format(flow.request.path))
    # ctx.log.info("host:{0}".format(flow.request.host))
    # ctx.log.info("port:{0}".format(flow.request.port))
    # ctx.log.info("method:{0}".format(flow.request.method))
    # ctx.log.info("headers:{0}".format(flow.request.headers.fields))
    # ctx.log.info("request_content:{0}".format(flow.request.content))
    # ctx.log.info("status_code:{0}".format(flow.response.status_code))
    # ctx.log.info("responseJson:{0}".format(flow.response.data.content))
    #
    # ret = redisCli.ping()
    # ctx.log.info("ping:{0}".format(ret))
    # # redisCli.zadd(name: "", mapping: {})


    info = dict()
    info["path"] = flow.request.path
    info["query"] = json.dumps(flow.request.query.fields)
    info["requestText"] = flow.request.text
    try:
        info["requestContent"] = str(flow.request.data.content, encoding="utf-8")
    except Exception as e:
        ctx.log.info("requestContent exception:{0}".format(e))

    info["host"] = flow.request.host
    info["url"] = flow.request.url
    info["method"] = flow.request.method
    info["status"] = flow.response.status_code
    info["responseText"] = flow.response.text
    try:
        info["respContent"] = str(flow.response.data.content, encoding="utf-8")
    except Exception as e:
        ctx.log.info("respContent exception:{0}".format(e))
    jsonInfo = json.dumps(info)
    ctx.log.info("jsonInfo:{0}".format(jsonInfo))
    redisCli.publish(msgChan, jsonInfo)


if __name__ == '__main__':
    opts = Options(listen_host='0.0.0.0', listen_port=8888, scripts=__file__)
    m = DumpMaster(opts)
    m.run()
